package com.houdoudou.customer.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class UniversalHttpPost {
	
	

	public static Map<String,Object> doPost(String  params[]){
		
		Map<String,Object> map= new HashMap<String,Object>();
        HttpResponse httpResponse;
        HttpEntity httpEntity;
        HttpClient httpClient = null;
        for(int i=0;i<params.length;i++)
       	System.out.println("params-------["+i+"]="+params[i]);
        NameValuePair pair1 =new BasicNameValuePair("affair", params[1]);
     /*
        String temp = null;
		try {
			temp = new String(params[2].getBytes(), "utf-8");
		//	temp=URLEncoder.encode( params[2].toString() );
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println("------------"+temp);
		*/
        NameValuePair pair2 = new BasicNameValuePair("jsonData",params[2]);
       
     
        List<NameValuePair> pairList = new ArrayList<NameValuePair>();
        pairList.add(pair1);
        pairList.add(pair2);
   
        InputStream  inputStream=null;
        String result="";
        try
        {
            HttpEntity requestHttpEntity = new UrlEncodedFormEntity(
                    pairList,HTTP.UTF_8);                  
            HttpPost httpPost = new HttpPost( params[0]);
          //  httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            //httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
           // httpPost.addHeader("Authorization", mToken);
          //  httpPost.addHeader("Content-Type", "application/json");    
   
           //  httpPost.addHeader("Content-Type", "text/html");    //这行很重要
            // httpPost.addHeader("charset", HTTP.UTF_8);         //这行很重要
            
            // 将请求体内容加入请求中
            httpPost.setEntity(requestHttpEntity);
            // 需要客户端对象来发送请求
            httpClient = new DefaultHttpClient();
            //Represents a collection of HTTP protocol and framework parameters  
            HttpParams timeparams = null;  
            timeparams = httpClient.getParams();  
            //set timeout  
            HttpConnectionParams.setConnectionTimeout(timeparams, 5000);  
            HttpConnectionParams.setSoTimeout(timeparams, 35000);  
            // 发送请求
             httpResponse = httpClient.execute(httpPost);

             // 处理返回结果   
             final int responseCode = httpResponse.getStatusLine().getStatusCode();  
             if (responseCode == HttpStatus.SC_OK){
            // 显示响应
        	httpEntity=httpResponse.getEntity();
				 inputStream= httpEntity.getContent();
				BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
				String line=null;
				
				while((line=bufferedReader.readLine())!=null){
					result=result+line;	
				}
				result=result.trim();
				System.out.println("服务器返回数据：-----"+result);
				
				map.put("PostState", true);
				map.put("PostResult", result);
				try{
					JSONObject resultJO= JSONObject.fromObject(result);
					Constant.CURRENT_TIME_SECOND=resultJO.getLong("currentTime");
				}catch(Exception e){e.printStackTrace();}
             }
             else{ System.out.println("----------------network error----------------");
                    map.put("PostState", false);
                    
             }
        } catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("can't connect to company's service");
				  map.put("PostState", false);
			/*	本广播要发送给主界面，暂时不发送，
             Intent intent = new Intent();//创建Intent对象  
             intent.setAction(Constants.ACTION_TOMAIN);  
       
             intent.putExtra("data", "can't connect to company's service");  
             sendBroadcast(intent);//发送广播  
             */
			}finally{
				try {
					if(inputStream!=null) inputStream.close();
					httpClient.getConnectionManager().shutdown();  
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}   
             
             
            
		   return map;
	}
	
}
